package com.sh.计数器限流.two;

import com.sh.RateLimiter;

public class Counter implements RateLimiter {
    public long lastRequestTime = getNowTime();
    public int requestCount = 0;  // 计数器
    public int maxCount = 100;  // 限流阈值
    public long interval = 1000;  // 时间间隔

    public boolean limit(){
        long now  = getNowTime();
        if ( now < lastRequestTime + interval){  // 如果在 interval 间隔内
            requestCount++;
            return requestCount <= maxCount;  // 计数器小于阈值吗？
        }else{
            requestCount = 1;  // 重置计数器
            lastRequestTime = now;  // 重置时间
            return true;
        }
    }


    public long getNowTime() {
        return System.currentTimeMillis();
    }


}
